package utils

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"regexp"
	"strings"
)

func IsNum(str string) bool {
	pattern := "\\d+" //反斜杠要转义
	result,_ := regexp.MatchString(pattern,str)
	//fmt.Println(str,"=",result)
	return result
}

func DbSave(data string) {
	file, err := os.OpenFile("./db/task.db", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Printf("创建文件失败:%v\n", err)
	}

	if file != nil {
		defer func(file *os.File) {
			file.Close()
		}(file)
	}

	file.Write([]byte(data+"\n"))
}

func DbList() []string  {
	file, err := os.Open("./db/task.db")
	if err != nil {
		log.Printf("打开文件失败:%v\n", err)
	}
	if file != nil {
		defer func(file *os.File) { file.Close() }(file)
	}

	//stat, err := file.Stat()
	//if err != nil {
	//	panic(err)
	//}
	//size := stat.Size()
	dataArr := []string{}
	buf := bufio.NewReader(file)
	for  {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		dataArr = append(dataArr, line)
		if err != nil {
			if err == io.EOF {
				fmt.Println("File read ok!")
				break
			} else {
				fmt.Println("Read file error!", err)
				return nil
			}
		}
	}
	return dataArr
}